
#include "precompiled.h"
#include "mimetypes.h"
#include "exception.h"
#include <logger/logger.h>
#include "helper.h"
class MimeTypesPrivate{
public:
	MimeTypesPrivate() {}
	~MimeTypesPrivate() {}
	QMap<QString, QString> mime;
};

MimeTypes::MimeTypes(QObject *parent) :
	QObject(parent), O_PRIVATE_CREATE(MimeTypes)
{
}

MimeTypes::~MimeTypes()
{
	O_PRIVATE_DELETE;
}

void MimeTypes::loadFile(const QString &filename){
    O_D(MimeTypes);

    LI.Info() << "Load mime types from file:" << filename;
    QFile mimes(filename);
    if (!mimes.open(QIODevice::ReadOnly)){
        throw new Exception("can't load file:" + filename);
    }

    QTextStream all(&mimes);
    while(!all.atEnd()){
        QString line = all.readLine();
        if (line.isEmpty())
            continue;
        QStringList l = line.split("=", QString::SkipEmptyParts);
        d->mime.insert(l[0], l[1]);
        LI.Trace() << "Mime:" << l[1];
    }
}

QString MimeTypes::mimeFor(const QString &ext){
    O_D(MimeTypes);
    LI.Trace() << "mimeFor:" << ext;
    if (!d->mime.contains(ext)){
        LI.Warning() << "mime not found";
        throw Exception(QString("%1 is not registered in Mime Type List").arg(ext));
    }

    QString m = d->mime.value(ext);
    LI.Trace() << "mime:" << m;
    return m;
}
